﻿Imports System.Data.Linq
Public Class CDonViController
    Dim objDataContext As QLyNganSachDataContext

    Public Sub New()
        objDataContext = New QLyNganSachDataContext
    End Sub
    Public Sub New(ByVal _obj As QLyNganSachDataContext)
        objDataContext = _obj
    End Sub
    Public Function SelectRecordByID(ByVal _id_DonVi As Integer) As tblDonVi
        Try
            Return (From r In objDataContext.tblDonVis
                    Where r.ID_DonVi = _id_DonVi
                    Select r).Single
        Catch ex As Exception
            Return Nothing
        End Try
    End Function
    Public Function SelectRecordByName(ByVal _ten As String) As tblDonVi
        Try
            Return (From r In objDataContext.tblDonVis
                    Where r.Ten.ToLower = _ten.ToLower.Trim
                    Select r).Single
        Catch ex As Exception
            Return Nothing
        End Try
    End Function
    Public Function SelectAllRecord() As IQueryable(Of tblDonVi)
        Try
            Return objDataContext.tblDonVis
        Catch ex As Exception
            Return Nothing
        End Try
    End Function
    Public Function InsertRecord(ByVal LocalTable As tblDonVi) As Integer
        Dim id As Integer = -1
        Try
            objDataContext.tblDonVis.InsertOnSubmit(LocalTable)
            objDataContext.SubmitChanges()
            id = LocalTable.ID_DonVi
        Catch ex As Exception
            Throw ex
        End Try
        Return id
    End Function
    Public Sub UpdateRecord(ByVal LocalTable As tblDonVi)
        Try
            objDataContext.tblDonVis.Attach(LocalTable)
            objDataContext.Refresh(RefreshMode.KeepCurrentValues, LocalTable)
            objDataContext.SubmitChanges(ConflictMode.ContinueOnConflict)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
    Public Sub UpdateRecordWithoutAttach(ByVal LocalTable As tblDonVi)
        Try
            objDataContext.Refresh(RefreshMode.KeepCurrentValues, LocalTable)
            objDataContext.SubmitChanges(ConflictMode.ContinueOnConflict)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Public Sub DeleteRecord(ByVal _id As Integer)
        Try
            objDataContext.tblDonVis.DeleteOnSubmit( _
              (From r In objDataContext.tblDonVis _
               Where r.ID_DonVi = _id).Single)
            objDataContext.SubmitChanges()
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
    Public Function CheckIfExists(ByVal _id As String, ByVal _ten As String) As Boolean
        Return objDataContext.tblDonVis.Any(Function(d) d.Ten = _ten And d.ID_DonVi <> _id)
    End Function
End Class
